/**********************************************************************
 Copyright (C) 2011 Jaakko Vuori

 This file is part of ShredMate.
 For more information, see <http://code.google.com/p/shredmate/>

 ShredMate is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 ShredMate is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with ShredMate.  If not, see <http://www.gnu.org/licenses/>.
 **********************************************************************/

#include "pcmgenerator.h"

#include <QDebug>

const qint64 MaxLength = 16384;

PCMGenerator::PCMGenerator(QObject *parent) : QIODevice(parent),
    m_data(NULL), m_length(0), m_currentPosition(0), m_looping(false)
{
    qDebug() << "PCMGenerator::PCMGenerator()";
    open(QIODevice::ReadOnly);
}

PCMGenerator::~PCMGenerator()
{
    qDebug() << "PCMGenerator::~PCMGenerator()";
    close();
}

void PCMGenerator::setData(const char* data, qint64 length)
{
    if (data == m_data && length == m_length)
        return;

    m_data = data;
    m_length = length;
    m_currentPosition = 0;
}

qint64 PCMGenerator::bufferLength() const
{
    return m_length;
}

qint64 PCMGenerator::readData(char* data, qint64 maxlen)
{
    //qDebug() << "PCMGenerator::readData" << maxlen;

    if (m_length <= 0)
        return 0;

    qint64 len = maxlen;
    if (len > MaxLength)
        len = MaxLength;

    qint64 left = m_length - m_currentPosition;
    if (len > left)
        len = left;

    //qDebug() << "m_currentPosition:" << m_currentPosition << "=" << m_currentPosition * 100 / m_length << "%";

    memcpy(data, m_data + m_currentPosition, len);

    m_currentPosition += len;
    if (m_currentPosition > m_length)
        qCritical() << "m_currentPosition exceeded m_length";

    if (m_currentPosition == m_length)
    {
        //qDebug() << "m_currentPosition:" << m_currentPosition << "=" << m_currentPosition * 100 / m_length << "%";
        m_currentPosition = 0;
        if (!m_looping)
            emit ended();
    }

    return len;
}

qint64 PCMGenerator::writeData(const char* data, qint64 len)
{
    Q_UNUSED(data);
    Q_UNUSED(len);

    return 0;
}
